<?php

namespace mpend\modules\passport\models;

use Yii;
use common\base\Model;
use mpend\models\User;

/**
 * 安全环境验证模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SecurityEnvCheckForm extends Model {

    /**
     * @var string 操作内容
     */
    public $operate;

    /**
     * @var integer 登录用户ID
     */
    public $user_id;

    /**
     * @var User 登录用户
     */
    private $_user = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['operate'], 'required'],
            ['user_id', 'validateUser'],
        ];
    }

    /**
     * 校验用户是否登录
     * @param string $attribute the attribute currently being validated
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $user = $this->getUser();
        if (!$user) {
            $this->addError($attribute, '账号信息校验失败');
        }
    }

    /**
     * 校验用户是否登录
     * @param string $attribute the attribute currently being validated
     */
    public function validateOperate($attribute) {
        if ($this->hasErrors()) {
            return;
        }
    }

    /**
     * 获取用户信息
     * @return UserMeta|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findOne($this->user_id);
        }
        return $this->_user;
    }

    /**
     * 校验短信验证码是否正确
     * @return bool whether the code was validated
     */
    public function check() {
        if (!$this->validate()) {
            return $this->dumpError('安全检测失败');
        }
        $user = $this->getUser();
        if (!$user) {
            return false;
        }
        $cache = $this->getCommonCache();
        $isValid = $cache->get('Security_' . $this->operate . '_' . $user->id);
        if ($isValid !== true) {
            return false;
        }
        return [
            '账号信息',
            '安全手机信息',
            '安全环境信息',
        ];
    }

}
